<script setup>
import { ref } from 'vue';
import { logout } from '@/api/exitSyst.js'; // 根据实际路径调整
import { useRouter } from 'vue-router';

const router = useRouter();
const isLoading = ref(false);
const errorMessage = ref('');

const handleLogout = async () => {
  isLoading.value = true;
  errorMessage.value = '';

  try {
    const result = await logout();

    if (result && result.code === 200) {
      // 修改：跳转到登录页面
      router.push('/login');
    } else {
      errorMessage.value = '退出登录失败，请重试';
    }
  } catch (error) {
    errorMessage.value = error.message || '退出登录发生错误';
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="header-container">
    <h1>欢迎使用碳中和系统</h1>
    <div class="logout-section">
      <button
          @click="handleLogout"
          :disabled="isLoading"
          class="logout-button"
      >
        <span v-if="isLoading">退出中...</span>
        <span v-else>退出登录</span>
      </button>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  /* 让头部区域更规整，可根据需求调整 */
  background-color: #e3f2fd;
}

/* 标题样式优化：自然居中，去掉不必要的偏移 */
h1 {
  margin: 0;
  font-size: 2rem;
  font-weight: 600;
}

.logout-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.logout-button {
  padding: 0.5rem 1rem;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-button:hover:not(:disabled) {
  background-color: #d32f2f;
}

.logout-button:disabled {
  background-color: #ffcdd2;
  cursor: not-allowed;
}

.error-message {
  color: #f44336;
  font-size: 0.8rem;
  margin-top: 0.5rem;
}
</style>